package com.roc.web.action.table;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.CompTransCount;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Action
@Component
@Scope("prototype")
@Namespace("/compTrans")
public class CompTransAction  extends PaginationBaseAction {
	
	private static final long serialVersionUID = 1L;
	private Logger logger=LogManager.getLogger(MerinfoTermAction.class);
	private CompTransSearchCondtion  searchCondition;
	

	@Autowired
	private IPagenitionService  pagenitionService;
	
	@Autowired
	private IExcelService excelService;
	
	private ByteArrayInputStream excelFile;
	
	
	
	@Action(value="init",results={ @Result(name="success",location="/pages/table/compTransJsp.jsp")})
	public String init(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode())||op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	   
	}
	
	@Action(value="queryCompTransList",results={@Result(name="success",location="/pages/table/compTransJsp.jsp")})
	public String queryCompTransList(){
		
		
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode())||op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()))
		{
		if(searchCondition==null){
			searchCondition=(CompTransSearchCondtion)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new CompTransSearchCondtion();
			}
		}
		try {
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
				List<CompTransCount> cclist=new ArrayList<CompTransCount>();
				//查询
				dealWith(cclist,searchRsList);
			
			getRequest().setAttribute("cclist", cclist);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询商终明细数据异常："+e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
		addActionError("无权限访问!!!");
		return ERROR;	
	}
	
	
	@Action(value="exportcompTransList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/table/compTransJsp.jsp") }) 
	public String  exportcompTransList() throws Exception{
		try {
			if(searchCondition==null){
				searchCondition=(CompTransSearchCondtion)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new CompTransSearchCondtion();
				}
			}
			
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<CompTransCount> staList = new ArrayList<CompTransCount>();
			dealWith(staList,searchRsList);
		
			SXSSFWorkbook  work=excelService.exportCompTransList(staList,searchCondition.getMinDate(),searchCondition.getMaxDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close();  
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
	}
	
	
	

	private List<CompTransCount> dealWith(List<CompTransCount> ccList, List<Object> searchRsList) {
		// TODO Auto-generated method stub
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				CompTransCount com=new CompTransCount();
				com.setTransDt(searchCondition.getMinDate()+"-"+searchCondition.getMaxDate());
				com.setOrgName(Constance.Null2EmptyTrim(obj[0]));
				com.setSumAmt(Constance.Null2EmptyTrim(obj[1]));
				com.setSumCount(Constance.Null2EmptyTrim(obj[2]));
				com.setCompanyName(Constance.Null2EmptyTrim(obj[3]));
				com.setActiveMchtCount(Constance.Null2EmptyTrim(obj[4]));
				com.setMchtFee(Constance.Null2EmptyTrim(obj[5]));
				com.setInCome(Constance.Null2EmptyTrim(obj[6]));
				ccList.add(com);
			}
		}
		return ccList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_COMP_TRANS_COUNT, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (CompTransSearchCondtion)getSession().getAttribute(SEARCH_SESSION_COMP_TRANS_COUNT);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public CompTransSearchCondtion getSearchCondition() {
		return searchCondition;
	}
	
	public void setSearchCondition(CompTransSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}


	public ByteArrayInputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(ByteArrayInputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName = "分公司交易统计" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}
}
